<script setup lang="js">
import './PreviewStyle.css'
import {nextTick, onMounted, ref} from "vue";
import $ from 'jquery';
import {defaultElementTypeProvider, hiprint} from 'vue-plugin-hiprint';
import {FormData} from './Component.js';

const printTemplate = ref(null);
const templateData = ref(null);
const initHiPrintComponent = () => {
  templateData.value = JSON.parse(localStorage.getItem('templateData'));
  $('#printTemplate').empty();
  hiprint.init({
    providers: [new defaultElementTypeProvider()],
    fontList: [{"title": '宋体', "value": 'SimSun'}],
  });
  hiprint.setConfig({
    movingDistance: 1,
    text: {
      supportOptions: [
        {
          name: 'styler',
          hidden: true
        },
        {
          name: 'formatter',
          hidden: true
        },
      ]
    }
  });
  const template = loadTemplate(templateData.value);
  const html = template.getHtml(FormData);
  $('#preview_content').html(html)
  printTemplate.value = template;
}

const loadTemplate = function (data) {
  return new hiprint.PrintTemplate({
    template: data,
    fontList: [
      {title: '宋体', value: 'SimSun'},
    ],
    dataMode: 1,
    history: true,
    willOutOfBounds: true,
    qtDesigner: true,
    onDataChanged: (type, json) => {
      console.log(type);
      console.log(json);
    },
    onUpdateError: (e) => {
      console.error(e);
    },
  });
}

const handlePrint = function () {
  printTemplate.value.print(templateData.value,
      {}, {
        callback: () => {
          console.log('print load done')
        }
      });
}

const handleToPdf = function () {
  printTemplate.value.toPdf(templateData.value,
      '测试导出Pdf文件', {
        scale: 4
      });
}

onMounted(() => {
  nextTick(() => {
    initHiPrintComponent();
  })
})
</script>

<template>
  <div class="preview-container">
    <div id="preview_content"></div>
    <div>
      <div class="preview-container-header-button-list">
        <div class="preview-container-header-button" @click="handlePrint">打印</div>
        <div class="preview-container-header-button" @click="handleToPdf">导出Pdf</div>
      </div>
    </div>
  </div>
</template>